package com.example.lotterysystem.controller;

import com.example.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.example.lotterysystem.common.exception.ControllerException;
import com.example.lotterysystem.common.pojo.CommonResult;
import com.example.lotterysystem.common.utils.JacksonUtil;
import com.example.lotterysystem.controller.param.ShortMessageLoginParam;
import com.example.lotterysystem.controller.param.UserPasswordLoginParam;
import com.example.lotterysystem.controller.param.UserRegisterParam;
import com.example.lotterysystem.controller.result.BaseUserInfoResult;
import com.example.lotterysystem.controller.result.UserLoginResult;
import com.example.lotterysystem.controller.result.UserRegisterResult;
import com.example.lotterysystem.service.UserService;
import com.example.lotterysystem.service.VerificationCodeService;
import com.example.lotterysystem.service.dto.UserDTO;
import com.example.lotterysystem.service.dto.UserLoginDTO;
import com.example.lotterysystem.service.dto.UserRegisterDTO;
import com.example.lotterysystem.service.enums.UserIdentityEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @auther falls_vc
 * description:
 * @date 2025/5/10  15:43
 */
@RestController
public class UserController {
    private static final Logger logger= LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private VerificationCodeService verificationCodeService;

    /**
     * 注册
     * @param param
     * @return
     */
    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(@Validated @RequestBody UserRegisterParam param){
        // 日志打印
        logger.info("[UserController /register] UserRegisterParam:{}", JacksonUtil.writeValueAsString(param));
        // 注册
        UserRegisterDTO userRegisterDTO=userService.register(param);
        return CommonResult.success(convertToUserRegisterResult(userRegisterDTO));
    }

    /**
     * 通过 qq邮箱  发送验证码
     * @param mail
     * @return
     */
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerification(String mail) {
        logger.info("sendVerificationCode mail:{}",mail);



        verificationCodeService.sendLoginVerificationCode(mail);

        return CommonResult.success(Boolean.TRUE);
    }
//    @RequestMapping("/verification-code/send")
//    public CommonResult<Boolean> sendVerification(String phoneNumber) {
//        logger.info("sendVerificationCode phoneNumber:{}",phoneNumber);
//        verificationCodeService.sendVerificationCode(phoneNumber);
//
//        return CommonResult.success(Boolean.TRUE);
//    }

    /**
     * 手机号/邮箱号 + 密码登录
     * @param param
     * @return
     */
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> userPasswordLogin(@Validated @RequestBody UserPasswordLoginParam param) {
        logger.info("userPasswordLogin UserPasswordLoginParam:{}",JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO=userService.login(param);
        UserLoginResult userLoginResult=convertToUserLoginResult(userLoginDTO);

        return CommonResult.success(userLoginResult);
    }

    /**
     * 采用邮箱号 + qq邮箱发送验证码校验登录
     * 代替手机号验证码登录（手机号验证码现在没申请到签名）
     * @param param
     * @return
     */
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> userMessageLogin(@Validated @RequestBody ShortMessageLoginParam param) {
        logger.info("userPasswordLogin ShortMessageLoginParam:{}",JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO=userService.login(param);
        UserLoginResult userLoginResult=convertToUserLoginResult(userLoginDTO);

        return CommonResult.success(userLoginResult);
    }

    /**
     * 查询用户信息
     * @param identity
     * @return
     */
    @RequestMapping("/base-user/find-list")
    public CommonResult<List<BaseUserInfoResult>> findBaseUserInfo(String identity) {
        logger.info("findBaseUserInfo identity:{}",identity);
        List<UserDTO> userDTOList=userService.findUserInfo(UserIdentityEnum.forName(identity));

        logger.info("findBaseUserInfo list :{}",JacksonUtil.writeValueAsString(userDTOList));
        return CommonResult.success(convertToBaseUserInfoResultList(userDTOList));
    }

    private List<BaseUserInfoResult> convertToBaseUserInfoResultList(List<UserDTO> userDTOList) {
        if (userDTOList.isEmpty()) {
            return Arrays.asList();// 返回空链表
        }
        return userDTOList.stream().map(userDTO->{
            BaseUserInfoResult baseUserInfoResult=new BaseUserInfoResult();
            baseUserInfoResult.setUserId(userDTO.getId());
            baseUserInfoResult.setUserName(userDTO.getUserName());
            baseUserInfoResult.setIdentity(userDTO.getIdentity().name());
            return baseUserInfoResult;
        }).collect(Collectors.toList());
    }


    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        UserLoginResult userLoginResult=new UserLoginResult();
        if(null == userLoginDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }
        userLoginResult.setToken(userLoginDTO.getToken());
        userLoginResult.setIdentity(userLoginDTO.getIdentity().name());

        return userLoginResult;
    }




    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO userRegisterDTO) {
        UserRegisterResult result=new UserRegisterResult();
        if(null == userRegisterDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        result.setUserId(userRegisterDTO.getUserId());
        return result;
    }
}
